<template>
  <HeadContainer class="mine-settings-username-email" :title="$t('title.usnMail')" @back="back">
    <form action="">
      <div class="mb-4 d-flex flex-column">
        <InputWrap
          v-model="form.nickname.value"
          :err-msg="form.nickname.error"
          :label="$t('label.displayName')"
          :placeholder="$t('placeholder.displayName')"
          trim
        ></InputWrap>
      </div>
      <div class="mb-4 d-flex flex-column">
        <InputWrap
          v-model="form.username.value"
          :err-msg="form.username.error"
          :label="$t('label.username')"
          :placeholder="$t('placeholder.username')"
          :subtitle="`@${form.username.value}`"
          trim
        ></InputWrap>
      </div>

      <v-divider></v-divider>
      <div class="mt-4">
        <div class="d-flex gap-row-16">
          <div @click="back()" class="cancel-light-btn w-100 d-flex justify-center align-center">
            {{ $t('common.cancel') }}
          </div>
          <div @click="onFormSave()" class="primary-btn w-100 d-flex justify-center align-center">
            {{ $t('common.save') }}
          </div>
        </div>
      </div>
      <div v-if="saveErrMsg" class="text-start err-msg font-size-14 font-weight-400 line-height-120 text-primary-x">
        {{ saveErrMsg }}
      </div>
    </form>
  </HeadContainer>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { onKeyStroke } from '@vueuse/core'
import { storeToRefs } from 'pinia'
import { useAccountStore } from '@/store/account'
import { usePopupMessageStore } from '@/store/popup-message'
import { $t } from '@/i18n'
import { useYup, validate } from '@/plugins/yup'
import InputWrap from '@/components/form/InputWrap.vue'
import HeadContainer from '@/components/layout/HeadContainer.vue'
import API from '@/http'

const emits = defineEmits(['toPage'])

function resetForm() {
  form.username.value = userData.value.username
  form.username.error = ''
  form.username.check = false
  form.nickname.value = userData.value.nickname
  form.nickname.error = ''
  form.nickname.check = false
  saveErrMsg.value = ''
}

function back() {
  emits('toPage', 2, 'settings')
  resetForm()
}

const accountStore = useAccountStore()
const { setUserData } = accountStore
const { userData } = storeToRefs(accountStore)
const { open } = usePopupMessageStore()

function createFormField(initialValue) {
  return reactive({
    value: initialValue,
    error: '',
    check: false,
  })
}

const form = reactive({
  username: createFormField(userData.value.username),
  nickname: createFormField(userData.value.nickname),
})

const saveErrMsg = ref('')

const yup = useYup()
const schemaNickname = yup.string().min(2).max(50)
const schemaUsername = yup
  .string()
  .min(4)
  .max(50)
  .matches(/^[a-zA-Z0-9+_]*$/)

const schemaNickNameWithAt = yup
  .string()
  .min(2)
  .max(50)
  .matches(/^[^@]*$/, $t('yup.string.withAt'))

const validateNicNameWithAt = async () => {
  await validate(schemaNickNameWithAt, form.nickname)
}

const onFormSave = async () => {
  const validateNickname = validate(schemaNickname, form.nickname)
  const validateUsername = validate(schemaUsername, form.username)

  const isNickNameChanged = form.nickname.value !== userData.value.nickname
  const isUserNameChanged = form.username.value !== userData.value.username

  try {
    // 情境1: 如果 username 和 nickname 都沒有更改
    if (!isNickNameChanged && !isUserNameChanged) {
      await Promise.all([validateNickname, validateUsername])
      console.log('請更改些什麼再來按我')
      open($t('common.setSuc'))
      emits('toPage', 2, 'settings')
    }
    // 情境2: 只針對 username 可以打後端資料
    else if (!isNickNameChanged && isUserNameChanged) {
      await Promise.all([validateNickname, validateUsername])
      const data = { username: form.username.value }
      await API.Auth.update({ data })
      setUserData(data)
      open($t('common.setSuc'))
      emits('toPage', 2, 'settings')
    }
    // 情境3: 只針對 nickname 驗證 validateNicNameWithAt
    else if (isNickNameChanged && !isUserNameChanged) {
      await validateNicNameWithAt()
      const data = { nickname: form.nickname.value }
      if (!form.nickname.error) {
        await API.Auth.update({ data })
        setUserData(data)
        open($t('common.setSuc'))
        emits('toPage', 2, 'settings')
      }

      // 情境4: 同時針對 username 和 nickname 進行驗證
    } else if (isNickNameChanged && isUserNameChanged) {
      await Promise.all([validateUsername, validateNicNameWithAt()])
      const data = {
        username: form.username.value,
        nickname: form.nickname.value,
      }
      if (!form.nickname.error) {
        await API.Auth.update({ data })
        setUserData(data)
        open($t('common.setSuc'))
        emits('toPage', 2, 'settings')
      }
    }

    saveErrMsg.value = ''
  } catch (e) {
    saveErrMsg.value = e.message
  }
}

onKeyStroke('Enter', onFormSave)
</script>
